<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-4">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
        <template #status_default="{ row }">
          <el-tag :type="handleHealthStatus(row) ? 'success' : 'danger'"
            >{{
              handleHealthStatus(row)
                ? t("person_manage.form.effective")
                : t("person_manage.form.expired")
            }}
          </el-tag>
        </template>
        <template #real_default="{ row }">
          <el-tag :type="handleRealNameStatus(row) ? 'primary' : 'info'"
            >{{
              handleRealNameStatus(row)
                ? t("person_manage.form.verified")
                : t("person_manage.form.unverified")
            }}
          </el-tag>
        </template>
      </AuTable>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { getPersonList, personDel, PersonProp } from "@/api/expiry/person";
import { useRouter } from "vue-router";
import { getStoreList } from "@/api/teaInfuser/store";
import { useI18n } from "vue-i18n";

// region 声明ref变量集合
const router = useRouter();
const { proxy } = getCurrentInstance();
const { t } = useI18n();

const formList = ref([
  {
    type: "input",
    label: "person_manage.form.name",
    key: "name",
    placeholder: "person_manage.form.enter_name"
  },
  {
    type: "select",
    label: "person_manage.form.store",
    key: "storeId",
    placeholder: "person_manage.form.select_store",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    options: []
  }
  // {
  //   type: "select",
  //   label: "健康证状态",
  //   key: "healthStatus",
  //   placeholder: "请选择健康证状态",
  //   valueKey: "value",
  //   labelKey: "label",
  //   options: [
  //     {
  //       label: "已过期",
  //       value: 0
  //     },
  //     {
  //       label: "生效中",
  //       value: 1
  //     }
  //   ]
  // },
  // {
  //   type: "select",
  //   label: "实名状态",
  //   key: "realNameStatus",
  //   placeholder: "请选择实名状态",
  //   valueKey: "value",
  //   labelKey: "label",
  //   options: [
  //     {
  //       label: "未实名",
  //       value: 0
  //     },
  //     {
  //       label: "已实名",
  //       value: 1
  //     }
  //   ]
  // }
]);
const personFormat = ({ row }) => {
  const obj = {
    M: t("person_manage.form.male"),
    F: t("person_manage.form.female")
  };
  return obj[row.gender] ?? "";
};
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    { field: "name", title: "person_manage.form.name", align: "center" },
    {
      field: "gender",
      title: "person_manage.form.gender",
      align: "center",
      formatter: personFormat,
      exportMethod: personFormat
    },
    { field: "storeName", title: "person_manage.form.store", align: "center" },
    {
      field: "expiry",
      title: "person_manage.form.health_certificate",
      align: "center",
      formatter: ({ row }) => `${row.expiryStart} - ${row.expiryEnd}`,
      exportMethod: ({ row }) => `${row.expiryStart} - ${row.expiryEnd}`
    },
    {
      field: "healthStatus",
      title: "person_manage.form.health_status",
      align: "center",
      slots: { default: "status_default" },
      exportMethod: ({ row }) =>
        handleHealthStatus(row)
          ? t("person_manage.form.effective")
          : t("person_manage.form.expired")
    },
    {
      field: "realNameStatus",
      title: "person_manage.form.real_name_status",
      align: "center",
      slots: { default: "real_default" },
      exportMethod: ({ row }) =>
        handleRealNameStatus(row)
          ? t("person_manage.form.verified")
          : t("person_manage.form.unverified")
    }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.TDELETE, ACTION_TYPE.EDIT],
  operateTools: [
    // {
    //   icon: "material-symbols:move-item-sharp",
    //   key: "move",
    //   name: "table.telRelocation",
    //   disableHandle: (row: DeviceProp) =>
    //     !(row.device_status == 0 && row.store_id != null)
    // }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        const { size, start_page, ...rest } = params;

        return getPersonList({
          size,
          start_page,
          personnel: rest
        });
      },
      param: () => {
        return {
          ...formRef.value.getFormData()
        };
      }
    }
  }
});

const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合
function handleHealthStatus(row: PersonProp) {
  const { expiryEnd } = row;
  const newDate = new Date();
  return newDate.getTime() < new Date(expiryEnd).getTime();
}

function handleRealNameStatus(row: PersonProp) {
  const { idCardFrontUrl, idCardBackUrl } = row;
  return idCardFrontUrl && idCardBackUrl;
}

// endregion

// region 组件事件的集合
const search = () => {
  tableRef.value.refresh();
};

type ActionType = {
  key: ACTION_TYPE;
  row: PersonProp;
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
  switch (key) {
    case ACTION_TYPE.TADD:
    case ACTION_TYPE.EDIT:
      router.push({
        path: "/personnel/personDetail",
        query: {
          id: row?.id
        }
      });
      break;
    case ACTION_TYPE.TDELETE:
      proxy.$auMessageBox
        .confirm(t("person_manage.form.delete_confirm"), t("notice.title"), {
          type: "error"
        })
        .then(() => {
          const checked = tableRef.value.getCheckboxRecords() as PersonProp[];
          const ids = checked.map(item => item.id);
          personDel({ ids }).then(() => {
            tableRef.value.refresh();
          });
        });
      break;
  }
};
// endregion

onMounted(() => {
  getStoreList({
    size: 0,
    start_page: 0
  }).then(res => {
    formRef.value.setFormProps("storeId", {
      options: res.data
    });
  });
});
</script>
